package com.jianjun.project.monitor.job;

import cn.hutool.core.convert.Convert;
import cn.hutool.http.Method;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.core.Path;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jianjun.common.constant.HttpStatus;
import com.jianjun.framework.web.domain.AjaxResult;
import com.jianjun.framework.web.interceptor.DataScope;
import com.jianjun.framework.web.page.TableDataInfo;
import com.jianjun.framework.web.render.ExcelWriterRender;
import com.jianjun.project.common.model.SysJobLog;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 调度日志操作处理
 *
 * @author source
 */
@Path(value = "/monitor/jobLog")
public class SysJobLogController extends Controller {
    @Inject
    SysJobLogService jobLogService;

    /**
     * 查询定时任务调度日志列表
     */
    @DataScope(permission = "monitor:job:list")
    public void list() {
        SysJobLog jobLog = JsonKit.parse(getKv().toJson(), SysJobLog.class);
        Page<SysJobLog> page = jobLogService.paginate(jobLog);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(page.getList());
        rspData.setTotal(page.getTotalRow());
        renderJson(rspData);
    }

    /**
     * 导出定时任务调度日志列表
     */
    @DataScope(permission = "monitor:job:export")
    public void export() {
        SysJobLog jobLog = JsonKit.parse(getKv().toJson(), SysJobLog.class);
        List<SysJobLog> list = jobLogService.selectJobLogList(jobLog);
        List<Map<String, Object>> mapList = list.stream().map(Model::toMap).collect(Collectors.toList());
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.write(mapList, true);
        render(new ExcelWriterRender(writer, jobLog.getClass().getSimpleName()));
    }


    @DataScope(permission = "monitor:job:query,monitor:job:remove")
    public void index() {
        String method = getRequest().getMethod();
        //查询
        if (Method.GET.name().equals(method)) {
            Long jobLogId = getParaToLong();
            renderJson(AjaxResult.success(jobLogService.selectJobLogById(jobLogId)));
        }
        //删除
        if (Method.DELETE.name().equals(method)) {
            jobLogService.deleteJobLogByIds(Convert.toLongArray(getPara()));
            renderJson(AjaxResult.success());
        }
    }


    /**
     * 清空定时任务调度日志
     */
    @DataScope(permission = "monitor:job:remove")
    public void clean() {
        jobLogService.cleanJobLog();
        renderJson(AjaxResult.success());
    }
}
